﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CoNatural.Data.VisualStudio.AddIn.Controls {
   public partial class SelectTemplateControl : UserControl {
		private static string[] LastTemplatePaths = null;
		private string TemplateDirectoryPath;

		public SelectTemplateControl(string projectPath) {
         InitializeComponent();
			if (LastTemplatePaths != null && LastTemplatePaths.Length > 0) {
				TemplateDirectoryPath = Path.GetDirectoryName(LastTemplatePaths[0]);
				ShowSelection();
			}
			else {
				TemplateDirectoryPath = Path.Combine(projectPath, "T4");
				selectedTemplatesCheckedListBox.Items.Clear();
			}
      }

      public void Initialize(string rootNamespace, IEnumerable<Model.DbObject> dbObjects) {
			dbObjectBindingSource.DataSource = dbObjects;
			dataGridView1.DataSource = dbObjectBindingSource;
			dataGridView1.Columns["Schema"].Visible = false;
			dataGridView1.Columns["Name"].Visible = false;
			dataGridView1.Columns["Selected"].Visible = false;
			dataGridView1.Columns["CommandName"].HeaderText = rootNamespace + "/[Command Name]";
      }

		private void selectTemplateButton_Click(object sender, EventArgs e) {
			openFileDialog1.InitialDirectory = TemplateDirectoryPath;
			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				if (openFileDialog1.FileNames.Length > 0) {
					LastTemplatePaths = openFileDialog1.FileNames;
					TemplateDirectoryPath = Path.GetDirectoryName(LastTemplatePaths[0]);
					ShowSelection();
				}
			}
		}

		private void ShowSelection() {
			selectedTemplatesCheckedListBox.Items.Clear(); 
			foreach (var item in LastTemplatePaths)
				selectedTemplatesCheckedListBox.Items.Add(item, true);
		}

		public IList<string> SelectedTemplates {
			get {
				var selected = new List<string>();

				MethodInvoker methodInvoker = () => {
					foreach (var item in selectedTemplatesCheckedListBox.CheckedItems)
						selected.Add(item.ToString());
				};

				if (InvokeRequired)
					Invoke(methodInvoker);
				else
					methodInvoker();

				return selected;
			}
		}
   }
}
